package com.tfswx.ocrengine.executor;

import com.alibaba.fastjson.JSONObject;
import com.tfswx.ocrengine.dto.OcrOutputDTO;
import com.tfswx.ocrengine.exception.AppException;
import com.tfswx.ocrengine.util.HttpUtil;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Ricky
 * @date 2021/1/11
 */
public class AliOcrExecutor extends AbstractOcrExecutor {
    private static final int SUCC_CODE = 200;

    @Override
    public OcrOutputDTO run(String wjnr) throws EngineException {
        String url = "http://" + getHost() + "/ocrapidocker/ocrservice.json";
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.put("method", Collections.singletonList("ocrService"));
        multiValueMap.put("img", Collections.singletonList(wjnr));
        multiValueMap.put("charInfo", Collections.singletonList("true"));
        multiValueMap.put("table", Collections.singletonList("true"));

        multiValueMap.put("prob", Collections.singletonList("true"));
        multiValueMap.put("rotate", Collections.singletonList("true"));
        multiValueMap.put("paragraph", Collections.singletonList("true"));
        multiValueMap.put("row", Collections.singletonList("true"));
        multiValueMap.put("recClassifyhw", Collections.singletonList("true"));
        multiValueMap.put("noStamp", Collections.singletonList("true"));

        List<String> languageList = new ArrayList<>();
        languageList.add("chn,sx");
        multiValueMap.put("language", languageList);

        JSONObject response;
        try {
            response = HttpUtil.postForObject(url, multiValueMap, JSONObject.class);
        } catch (Exception e) {
            throw new EngineException("引擎调用失败：" + e.getMessage(), e);
        }
        Integer code = response.getInteger("code");
        if (code != SUCC_CODE) {
            throw new AppException(response.getString("errMsg"));
        }
        JSONObject data = response.getJSONObject("data");

        return data.toJavaObject(OcrOutputDTO.class);
    }
}
